package com.coocare.licence.config.plugins.logging.factory;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.coocare.licence.entity.SysLog;
import com.coocare.licence.service.ISysLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 日 志 异 步 工 厂
 *
 * @author adamdiu
 */
@Component
@RequiredArgsConstructor
public class LoggingFactory {

    /**
     * 引 入 日 志 服 务
     */
    private final ISysLogService loggingService;

    /**
     * 执 行 日 志 入 库 操 作
     */
    @Async
    public void record(SysLog logging, ServletRequestAttributes attributes) {
        // 将主线程的请求信息，设置到子线程中
        RequestContextHolder.setRequestAttributes(attributes);
        UserAgent ua = UserAgentUtil.parse(attributes.getRequest().getHeader("User-Agent"));
        logging.setUserAgent(ua.getBrowser().getName() + "-" + ua.getVersion());
        // 异 步 操 作 无 返 回 值 处 理
        loggingService.save(logging);
    }
}
